package workwx

import (
	"codeup.aliyun.com/5f9118049cffa29cfdd3be1c/util/robot/internal/helper"
	"codeup.aliyun.com/5f9118049cffa29cfdd3be1c/util/robot/internal/httpclient"
	"fmt"
	"io"
	"net/http"
)

// CheckHttpResponseStatusCode 检查HTTP响应状态码
func CheckHttpResponseStatusCode(method, url string, statusCode int) error {
	if statusCode/100 != 2 {
		return fmt.Errorf("%w; http response status code: %v, %s %s", httpclient.ErrRequest, statusCode, method, url)
	}
	return nil
}

func GetJSON(url string, respBody any) (http.Header, error) {
	resp, err := httpclient.Get(url)
	if err != nil {
		return nil, fmt.Errorf("%w; %s %s, %v", httpclient.ErrRequest, http.MethodGet, url, err)
	}
	defer func(Body io.ReadCloser) {
		_ = Body.Close()
	}(resp.Body)

	if err := CheckHttpResponseStatusCode(http.MethodGet, url, resp.StatusCode); err != nil {
		return nil, err
	}

	return resp.Header, helper.JsonDecode(resp.Body, respBody)
}

// postJSON http post json
func postJSON(url string, reqBody, respBody any) (http.Header, error) {
	body, err := helper.JsonEncode(reqBody)
	if err != nil {
		return nil, err
	}

	resp, err := httpclient.Post(url, httpclient.HdrValApplicationJson, body)
	if err != nil {
		return nil, fmt.Errorf("%w; %s %s, %v", httpclient.ErrRequest, http.MethodPost, url, err)
	}
	defer func(Body io.ReadCloser) {
		_ = Body.Close()
	}(resp.Body)

	if err := CheckHttpResponseStatusCode(http.MethodPost, url, resp.StatusCode); err != nil {
		return nil, err
	}

	return resp.Header, helper.JsonDecode(resp.Body, respBody)
}

func PostFileJSON(url, fieldName, fileName string, respBody any) (http.Header, error) {
	resp, err := httpclient.PostFile(url, fieldName, fileName)
	if err != nil {
		return nil, fmt.Errorf("%w; %s %s, %v", httpclient.ErrRequest, http.MethodPost, url, err)
	}
	defer func(Body io.ReadCloser) {
		_ = Body.Close()
	}(resp.Body)

	if err := CheckHttpResponseStatusCode(http.MethodPost, url, resp.StatusCode); err != nil {
		return nil, err
	}

	return resp.Header, helper.JsonDecode(resp.Body, respBody)
}
